﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Cuckoo.TaskSchedule
{
    /// <summary>
    /// 实际的计时器类，
    /// 其他计时器绑定该计时器的计时事件以获得时间序列
    /// </summary>
	public class BaseTimer : ITimer
	{
		private BaseTimer()
		{
		}

		private static BaseTimer _Instance;
		/// <summary>
		/// 基础计时器
		/// 用于产生时间序列，其他计时器与该计时器绑定
		/// </summary>
		public static BaseTimer Instance
		{
			get
			{
				if (_Instance == null)
				{
					_Instance = new BaseTimer();
					_Instance.Work();
				}
				return _Instance;
			}
		}

		/// <summary>
		/// 计时事件
		/// </summary>
		public event SecondTriggerHandle SecondTrigger;

		/// <summary>
		/// 触发计时事件
		/// </summary>
		public void OnSecondTrigger()
		{
			if (SecondTrigger != null)
			{
				SecondTrigger();
			}
		}

		/// <summary>
		/// 工作线程
		/// </summary>
		Thread thWorker = null;

		/// <summary>
		/// 运行计时线程
		/// </summary>
		public void Work()
		{
			if (thWorker != null)
			{
				if (thWorker.IsAlive)
				{
					thWorker.Abort();
				}
			}
			thWorker = new Thread(StartWork);
			thWorker.IsBackground = true;
			TotalSecond = 0;
			thWorker.Start();
		}

		/// <summary>
		/// 开始计时工作
		/// </summary>
		private void StartWork()
		{
			while (true)
			{
				Thread.Sleep(1000);
				TotalSecond++;
				OnSecondTrigger();
			}
		}

		/// <summary>
		/// 已运行时间
		/// </summary>
		public long TotalSecond { get; set; }
	}
}
